<template>
  <div id="app">
    <!-- 公共头部组件 -->
    <common-header v-if="isShowHeaderAndFooter"
      :key="$route.fullPath"></common-header>

    <!-- 路由视图，相当于router-view -->
    <div :key="$route.name">
      <nuxt />
    </div>
    <!-- 公共底部组件 -->
    <common-footer v-if="isShowHeaderAndFooter"></common-footer>

    <backtop v-if="scrollTop && isShowHeaderAndFooter"></backtop>
  </div>
</template>

<script>
import elementsVisible from '~/mixins/elements-visible'
import { mapState, mapMutations } from 'vuex'
export default {
  mixins: [elementsVisible],
  data() {
    return {
      redirectArr: ['lang-login', 'login'],
      scrollTop: false,
    }
  },
  async fetch() {
    try {
      const res = await this.$axiosApi.bigAdvertisementUser()
      if (
        res &&
        res.code === 200 &&
        res.data &&
        this.hasRealVal(res.data.advertisement)
      ) {
        this.SET_TOP_ADVERTISER(res.data.advertisement)
      } else {
        this.SET_TOP_ADVERTISER(null)
      }
    } catch (error) {
      console.log(error)
    }
  },
  computed: {
    ...mapState({
      toolify_isLogin: (state) => state.toolify_isLogin,
    }),
    isShowHeaderAndFooter() {
      return (
        this.$route &&
        this.$route.name &&
        this.$route.name !== 'lang-login' &&
        this.$route.name !== 'login' &&
        this.$route.name !== 'lang-register' &&
        this.$route.name !== 'register' &&
        this.$route.name !== 'lang-resetPassword' &&
        this.$route.name !== 'resetPassword' &&
        this.$route.name !== 'lang-forgetPassword' &&
        this.$route.name !== 'forgetPassword' &&
        this.$route.name !== 'lang-forgetPassword-sendSuccess' &&
        this.$route.name !== 'forgetPassword-sendSuccess'
      )
    },
  },
  created() {
    if (process.browser) {
      if (process.env.NODE_ENV !== 'development') {
        let domain = window.location.hostname
        if (
          domain !== 'www.toolify.ai' &&
          domain !== 'toolify-pre.ffhhkk.com' &&
          domain !== 'toolify.tangshu.com'
        ) {
          window.location.href = 'https://www.toolify.ai'
        }
      }

      let searchTools = window.localStorage.getItem('toolify-searchTools')
      let searchCategory = window.localStorage.getItem('toolify-searchCategory')
      if (searchTools && searchCategory) {
        this.SET_SearchTools(JSON.parse(searchTools))
        this.SET_SearchCategory(JSON.parse(searchCategory))
        this.SET_SearchLoading(false)
      }
    }
    this.getUserinfo()
  },
  watch: {
    $route: {
      handler() {
        let redirect = this.$cookies.get('toolifyRedirect')
        if (redirect && !this.redirectArr.includes(this.$route.name)) {
          this.$cookies.remove('toolifyRedirect')
        }
      },
      deep: true,
      immediate: true,
    },
  },
  mounted() {
    this.getSearchCacheList()
    if (process.browser) {
      if (!this.$cookies.get('utm') && document.referrer) {
        this.$cookies.set('utm', document.referrer, {
          maxAge: 60 * 60 * 24 * 1,
          path: '/',
        })
      }
      if (Intl.DateTimeFormat().resolvedOptions().timeZone) {
        this.$cookies.set(
          'timezone',
          Intl.DateTimeFormat().resolvedOptions().timeZone,
          {
            maxAge: 60 * 60 * 24 * 30,
            path: '/',
          }
        )
      }
      window.addEventListener('scroll', this.onSroll)
    }
  },
  methods: {
    ...mapMutations([
      'SET_USERINFO',
      'SET_SearchLoading',
      'SET_SearchTools',
      'SET_SearchCategory',
      'SET_ADVERTISER',
      'SET_TOP_ADVERTISER',
    ]),
    async getUserinfo() {
      if (this.toolify_isLogin) {
        try {
          const res = await this.$axiosApi.userinfo()
          if (res && res.code === 200 && res.data && res.data.user) {
            this.SET_USERINFO(res.data.user)
            this.SET_ADVERTISER(res.data.advertiser)
          }
        } catch (error) {}
      }
    },
    async getSearchCacheList() {
      try {
        let uri
        if (process.browser) {
          uri = window.location.origin
        }
        this.SET_SearchLoading(true)
        this.$axios
          .$get(
            `${
              process.env.NODE_ENV === 'development' || !uri ? '' : uri
            }/self-api/v1/tools/search/search-cue-list-v1.json`
          )
          .then((res) => {
            this.SET_SearchLoading(false)
            this.SET_SearchTools(res.tool)
            this.SET_SearchCategory(res.category)
          })
          .catch((error) => {
            this.SET_SearchLoading(false)
            console.error('请求数据失败：', error)
          })
      } catch (error) {
        this.SET_SearchLoading(false)
      }
    },

    onSroll() {
      var scrollTop =
        document.documentElement.scrollTop || document.body.scrollTop

      if (scrollTop > 400) {
        this.scrollTop = true
      } else {
        this.scrollTop = false
      }
    },
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.onSroll, false)
  },
}
</script>

<style lang='scss' scoped>
.pt-18 {
  padding-top: 4.5rem;
}
</style>
